<route lang="json5" type="page">
{
    layout: "default",
    style: {
        navigationBarTitleText: "邀请下级分销",
    },
}
</route>

<template>
    <view class="m-base-box m-invitation">
        <view class="u-bg">
            <image src="/src/static/mp-weixin/images/fxhb.jpg" mode="scaleToFill" />
        </view>
        <view class="u-qrcode">
            <image :src="xcxPic" mode="scaleToFill" v-if="xcxPic" style="border-radius: 50%" />
        </view>
        <wd-fab v-model="fabShow" position="left-top" draggable>
            <template #trigger>
                <wd-button @click="handleSaveImage" custom-class="custom-button" type="primary" round>
                    保存至相册
                </wd-button>
            </template>
        </wd-fab>
    </view>
</template>

<script lang="ts" setup>
import { generateWxaQrCodeUsingPost } from "@/service/app";
import { useUserStore } from "@/store/user";
import { useToast } from "wot-design-uni";
const toast = useToast();
const userStore = useUserStore();
const xcxPic = ref("");
const fabShow = ref(false);
const startPic = () => {
    let page = "pages/login/register";
    toast.loading({
        loadingType: "ring",
        msg: "加载中...",
    });
    // 环境参数,release正式环境,trial体验版,develop开发版,默认release
    generateWxaQrCodeUsingPost({
        body: {
            page: page,
            scene: `${userStore.userInfo?.id}`,
            envVersion: import.meta.env.VITE_APP_QRCODE_TYPE,
            checkPath: false,
            type: "fz",
        },
    }).then((res) => {
        toast.close();
        console.log(res);
        xcxPic.value = res.data;
    });
};
function saveBase64ToPhotoAlbum(base64Data) {
    // 1. 去除Base64头部信息（如："data:image/png;base64,"）
    const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");

    // 2. 转换为ArrayBuffer
    const arrayBuffer = uni.base64ToArrayBuffer(base64);

    // 3. 生成临时文件路径
    const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;

    // 4. 写入文件
    const fs = uni.getFileSystemManager();
    return new Promise((resolve, reject) => {
        fs.writeFile({
            filePath,
            data: arrayBuffer,
            encoding: "binary",
            success: () => {
                // 5. 保存到相册
                uni.saveImageToPhotosAlbum({
                    filePath,
                    success: () => resolve("保存成功"),
                    fail: (err) => reject("保存失败，请检查权限：" + err.errMsg),
                });
            },
            fail: (err) => reject("文件写入失败：" + err.errMsg),
        });
    });
}

// 调用示例
async function handleSaveImage() {
    try {
        // 示例Base64数据，实际替换为你的数据
        await saveBase64ToPhotoAlbum(xcxPic.value);
        uni.showToast({ title: "保存成功", icon: "success" });
        console.error("保存图片成功");
    } catch (error) {
        console.error("保存图片失败 error：", error);
        uni.showToast({ title: error, icon: "none" });
        // 处理权限被拒绝的情况
        if (error.includes("authorize")) {
            uni.openSetting({}); // 引导用户打开权限设置
        }
    }
}

onShow(() => {
    startPic();
});
</script>

<style lang="scss" scoped>
.m-invitation {
    position: relative;
    .u-bg {
        width: 100%;
        height: 100%;
    }
    .u-qrcode {
        position: fixed;
        right: 20rpx;
        bottom: 40rpx;
        image {
            width: 400rpx;
            height: 400rpx;
        }
    }
}
</style>
